package com.wande.dataplatform.filecollection.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.wande.common.core.domain.R;
import com.wande.common.web.core.BaseController;
import com.wande.dataplatform.filecollection.performance.PerformanceMonitor;
import com.wande.dataplatform.filecollection.service.IFileCollectionService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 文件采集监控控制器
 * 提供性能指标和监控数据查询接口
 *
 * @author wande
 */
@RestController
@RequestMapping("/dataplatform/file-collection/monitor")
@RequiredArgsConstructor
public class FileCollectionMonitorController extends BaseController {

    private final PerformanceMonitor performanceMonitor;
    private final IFileCollectionService fileCollectionService;

    /**
     * 获取全局性能统计
     */
    @SaCheckPermission("dataplatform:file-collection:monitor:view")
    @GetMapping("/statistics")
    public R<Map<String, Object>> getStatistics() {
        Map<String, Object> stats = performanceMonitor.getStatistics();
        return R.ok(stats);
    }

    /**
     * 获取任务性能指标
     */
    @SaCheckPermission("dataplatform:file-collection:monitor:view")
    @GetMapping("/task/{taskId}/metrics")
    public R<PerformanceMonitor.TaskMetrics> getTaskMetrics(@PathVariable Long taskId) {
        PerformanceMonitor.TaskMetrics metrics = performanceMonitor.getTaskMetrics(taskId);
        return R.ok(metrics);
    }

    /**
     * 获取全局性能指标
     */
    @SaCheckPermission("dataplatform:file-collection:monitor:view")
    @GetMapping("/global/metrics")
    public R<PerformanceMonitor.GlobalMetrics> getGlobalMetrics() {
        PerformanceMonitor.GlobalMetrics metrics = performanceMonitor.getGlobalMetrics();
        return R.ok(metrics);
    }

    /**
     * 获取任务监控数据
     */
    @SaCheckPermission("dataplatform:file-collection:monitor:view")
    @GetMapping("/task/overview")
    public R<Map<String, Object>> getTaskOverview() {
        Map<String, Object> overview = new HashMap<>();
        
        // 获取性能统计
        Map<String, Object> stats = performanceMonitor.getStatistics();
        overview.putAll(stats);
        
        // 可以添加更多监控数据
        // 例如：最近的任务列表、错误率等
        
        return R.ok(overview);
    }

    /**
     * 获取文件监控数据
     */
    @SaCheckPermission("dataplatform:file-collection:monitor:view")
    @GetMapping("/file/overview")
    public R<Map<String, Object>> getFileOverview() {
        Map<String, Object> overview = new HashMap<>();
        
        PerformanceMonitor.GlobalMetrics metrics = performanceMonitor.getGlobalMetrics();
        overview.put("totalFiles", metrics.getTotalFiles().get());
        overview.put("totalFileSize", metrics.getTotalFileSize().get());
        overview.put("totalRecords", metrics.getTotalRecords().get());
        
        // 计算平均值
        long totalFiles = metrics.getTotalFiles().get();
        if (totalFiles > 0) {
            overview.put("avgFileSize", metrics.getTotalFileSize().get() / totalFiles);
            overview.put("avgRecordsPerFile", metrics.getTotalRecords().get() / totalFiles);
        }
        
        return R.ok(overview);
    }

    /**
     * 获取数据监控指标
     */
    @SaCheckPermission("dataplatform:file-collection:monitor:view")
    @GetMapping("/data/overview")
    public R<Map<String, Object>> getDataOverview() {
        Map<String, Object> overview = new HashMap<>();
        
        PerformanceMonitor.GlobalMetrics metrics = performanceMonitor.getGlobalMetrics();
        overview.put("totalRecords", metrics.getTotalRecords().get());
        overview.put("totalParseTime", metrics.getTotalParseTime().get());
        overview.put("totalLoadTime", metrics.getTotalLoadTime().get());
        
        // 计算吞吐量
        long totalRecords = metrics.getTotalRecords().get();
        long totalParseTime = metrics.getTotalParseTime().get();
        long totalLoadTime = metrics.getTotalLoadTime().get();
        
        if (totalRecords > 0) {
            if (totalParseTime > 0) {
                overview.put("parseRecordsPerSecond", totalRecords * 1000 / totalParseTime);
            }
            if (totalLoadTime > 0) {
                overview.put("loadRecordsPerSecond", totalRecords * 1000 / totalLoadTime);
            }
        }
        
        return R.ok(overview);
    }

    /**
     * 获取系统资源监控
     */
    @SaCheckPermission("dataplatform:file-collection:monitor:view")
    @GetMapping("/system/resources")
    public R<Map<String, Object>> getSystemResources() {
        Map<String, Object> resources = new HashMap<>();
        
        Runtime runtime = Runtime.getRuntime();
        
        // 内存使用情况
        long totalMemory = runtime.totalMemory();
        long freeMemory = runtime.freeMemory();
        long usedMemory = totalMemory - freeMemory;
        long maxMemory = runtime.maxMemory();
        
        resources.put("totalMemory", totalMemory);
        resources.put("freeMemory", freeMemory);
        resources.put("usedMemory", usedMemory);
        resources.put("maxMemory", maxMemory);
        resources.put("memoryUsagePercent", (double) usedMemory / maxMemory * 100);
        
        // CPU核心数
        resources.put("availableProcessors", runtime.availableProcessors());
        
        // 线程数
        resources.put("activeThreadCount", Thread.activeCount());
        
        return R.ok(resources);
    }

    /**
     * 清除任务性能指标
     */
    @SaCheckPermission("dataplatform:file-collection:monitor:manage")
    @DeleteMapping("/task/{taskId}/metrics")
    public R<Void> clearTaskMetrics(@PathVariable Long taskId) {
        performanceMonitor.clearTaskMetrics(taskId);
        return R.ok();
    }
}
